package com.tangsm.spring.boot.filter.common.filter;

import com.tangsm.spring.boot.filter.common.utli.HttpUtils;
import com.tangsm.spring.boot.filter.common.wrapper.RequestWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Java配置实现Filter过滤器
 * @author tangsm
 **/
public class ConfigRegisterFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(ConfigRegisterFilter.class);

    @Override
    public void init(FilterConfig config) throws ServletException {
        log.info("ConfigRegisterFilter注解实现Filter过滤器，过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("ConfigRegisterFilter注解实现Filter过滤器，执行过滤操作");

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        log.info("ConfigRegisterFilter注解实现Filter过滤器，请求URI：{}", httpServletRequest.getRequestURI());

        // json请求打印body信息
        if (HttpUtils.isJsonContent(request)) {
            // 包装HttpServletRequest，目的是让其输入流可重复读
            RequestWrapper requestWrapper = new RequestWrapper((HttpServletRequest) request);
            log.info("ConfigRegisterFilter注解实现Filter过滤器，请求Body：{}", requestWrapper.getBody());
            chain.doFilter(requestWrapper, response);
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        log.info("ConfigRegisterFilter注解实现Filter过滤器，过滤器销毁");
    }
}
